package com.yixinsoft.basic.mapper.base;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static org.apache.ibatis.jdbc.SqlBuilder.BEGIN;
import static org.apache.ibatis.jdbc.SqlBuilder.DELETE_FROM;
import static org.apache.ibatis.jdbc.SqlBuilder.SQL;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;

import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;

/**
 * Created by hqy on 2016/06/18
 */
public class MyMapperProvider extends MapperTemplate {

	public MyMapperProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
		super(mapperClass, mapperHelper);
	}

	public SqlNode deleteByIds(MappedStatement ms) {
		Class<?> entityClass = getEntityClass(ms);
		Set<EntityColumn> entityColumns = EntityHelper.getPKColumns(entityClass);
		EntityColumn entityColumn = null;
		for (EntityColumn entity : entityColumns) {
			entityColumn = entity;
			break;
		}
		EntityColumn column = entityColumn;
		List<SqlNode> sqlNodes = new ArrayList<>();
		//开始拼sql
		BEGIN();
		//delete from table
		DELETE_FROM(tableName(entityClass));
		//得到sql
		String sql = SQL();
		//静态SQL部分
		sqlNodes.add(new StaticTextSqlNode(sql + " WHERE " + column.getColumn() + " IN "));
		//构造foreach sql
		SqlNode foreach = new ForEachSqlNode(ms.getConfiguration(), new StaticTextSqlNode("#{" + column.getProperty() + "}"), "ids", "index", column.getProperty(), "(", ")", ",");
		sqlNodes.add(foreach);
		return new MixedSqlNode(sqlNodes);
	}
}
